﻿#include <QRandomGenerator>
#include "mainwindow.h"
#include "ui_MainWindow.h"


MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    QUrl url = "file:///" + qApp->applicationDirPath() + "/file/hello_world.html";

    ui->webEngineView->load(url);

    timer = new QTimer(this);

    connect(ui->btnSend, &QPushButton::clicked, this, &MainWindow::on_btnSend_clicked);
    connect(ui->btnStart, &QPushButton::clicked, this, &MainWindow::on_btnStart_clicked);
    connect(ui->btnStop, &QPushButton::clicked, this, &MainWindow::on_btnStop_clicked);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateText);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::on_btnSend_clicked() {
    QString text = "test test test";
    QString script = QString("showText('%1');").arg(text);

    ui->webEngineView->page()->runJavaScript(script);
}

void MainWindow::on_btnStart_clicked() {
    if (timer) {
        if (!timer->isActive()) {
            timer->start(1000);
        }
    }
}

void MainWindow::on_btnStop_clicked() {
    if (timer) {
        if (timer->isActive()) {
            timer->stop();
        }
    }
}

void MainWindow::updateText() {
    QString text;

    int randNum = QRandomGenerator::global()->bounded(1, 6);

    for (int i = 0; i < randNum; i++) {
        text.append("test ");
    }

    text.chop(1);

    QString script = QString("showText('%1');").arg(text);

    ui->webEngineView->page()->runJavaScript(script);
}
